package com.ysw.rpc.server.handler.inbound;

import com.ysw.rpc.common.messages.Request;
import com.ysw.rpc.common.messages.Response;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Optional;
import java.util.concurrent.Executor;

/**
 * @author YinShangwen
 * @since 2023/4/18 10:24
 */
@ChannelHandler.Sharable
public abstract class AbstractRequestHandler extends SimpleChannelInboundHandler<Request> {
    private final Executor executor;

    public AbstractRequestHandler(Executor executor) {
        this.executor = executor;
    }

    /**
     * 具体处理方法
     *
     * @param msg msg
     * @return res
     * @throws Exception e
     */
    public abstract Object handler(Request msg) throws Exception;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Request msg) {
        executor.execute(() -> {
            Response res = Response.init(msg);
            try {
                res.setResult(handler(msg));
            } catch (Exception e) {
                res.setError(Optional.ofNullable(e.getCause()).orElse(e).getMessage());
            }
            ctx.channel().writeAndFlush(res);
        });
    }
}

